﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace SoufunData
{
    public partial class BUpdateFileForm : DevExpress.XtraEditors.XtraForm
    {
        
        private string _proName;
        private bool _hasAddNewFiles;
        private bool _isUpdatingFile;


        public BUpdateFileForm(string projectName)
        {
            InitializeComponent();
            imageList1.Images.Add(Properties.Resources.WordFile_52x51);
            openFileDialog1.Filter = "Word文件|*.doc;*.docx|Excel文件|*.xls;*.xlsx";
            _proName = projectName;
        }
         
        private void btn_addImages_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            string[]  files = openFileDialog1.FileNames;            
            foreach (string file in files)
            {
                if (File.Exists(file))
                { 
                    if (listView1.Items.Find(file, false).Length>0) 
                    {
                       XtraMessageBox.Show("您已选择了添加【" 
                           + file.Substring(file.LastIndexOf("\\")+1)+
                           "】,请不要重复添加同一文件！");
                        continue;
                    }
                     
                    ListViewItem item = new ListViewItem();
                    item.Name = file;
                    item.Text = file.Substring(file.LastIndexOf("\\") + 1);
                    string fileType = file.Substring(file.LastIndexOf('.') + 1);
                    switch (fileType)
                    {
                        case "doc":
                            item.ImageIndex = 0;
                            break;
                        case "docx":
                            item.ImageIndex = 0;
                            break;
                        default:
                            item.ImageIndex = 0;
                            break;
                    } 
                    listView1.Items.Add(item);
                  
                }
                 
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            List<string> delList = new List<string>();
            foreach (ListViewItem item in listView1.SelectedItems)
            { 
                delList.Add(item.Name);                
                listView1.Items.Remove(item);
            } 
        }

        private List<string> _fileList = new List<string>();

        private void btn_upLoad_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count==0)
            {
                XtraMessageBox.Show("请先选择想要添加上传的文件!");
                return;
            }
            _fileList.Clear();
            foreach (ListViewItem item in listView1.Items)
            {
                _fileList.Add(item.Name);
            }
            progressBarControl1.Properties.Maximum = _fileList.Count;
            progressBarControl1.Properties.Minimum = 0;
            progressBarControl1.Position = 0;
            progressBarControl1.Visible = true;
            btn_upLoad.Enabled = false;
            btn_addFiles.Enabled = false;
            btn_delete.Enabled = false;

            Thread tUpload = new Thread(UpLoadImages) {IsBackground = true};
            tUpload.Start();
        }

        private void UpLoadImages()
        {
            try
            {
                _isUpdatingFile = true;
                string[] ftpConfig = ConfigClass.GetFtpConfig();
                FTPclient ftpClient = new FTPclient(ftpConfig[0], ftpConfig[1],
                    ftpConfig[2]);
                string rootPath = _proName + "/文件/";

                List<string> dirList = ftpClient.ListDirectory("");
                if (!dirList.Contains(_proName))
                {
                    ftpClient.FtpCreateDirectory(_proName);
                }
                List<string> imgDirList = ftpClient.ListDirectory("/" + _proName + "/");
                if (!imgDirList.Contains("文件"))
                {
                    ftpClient.FtpCreateDirectory(_proName + "/文件");
                }
                int failed = 0;
                //   string strImgList = "|";

                SqlClass sqlClass = new SqlClass();

                foreach (string file in _fileList)
                {
                    //string name = DateTime.Now.ToString("yyMMddHHmmss") +
                    //              DateTime.Now.Millisecond.ToString("d4")
                    //              + file.Substring(file.LastIndexOf("."));
                    string strFileName = file.Substring(file.LastIndexOf('\\') + 1);
                    string webPath = rootPath + strFileName;
                    bool result = ftpClient.Upload(file, webPath);
                    if (result)
                    {
                        //  strImgList += name + "|";
                        BeginInvoke(new MethodInvoker(() =>
                        {
                            progressBarControl1.Position++;
                        }));
                        bool updateDb = sqlClass.BusinessBasicUpdateFilePath(
                            _proName, strFileName);

                        if (!updateDb)
                        {
                            XtraMessageBox.Show("请检测数据库连接是否正常！");
                            return;
                        }
                        _hasAddNewFiles = true;
                    }
                    else
                    {
                        failed++;
                    }
                }

                string strNotice = "上传完毕，成功上传"
                                   + (_fileList.Count - failed) + "个文件!";
                if (failed > 0)
                {
                    strNotice += "失败" + failed + "个！";
                }
                _isUpdatingFile = false;
                XtraMessageBox.Show(strNotice);

                _fileList.Clear();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("异常：" + ex.Message);
            }
          
            BeginInvoke(new MethodInvoker(() =>
                {
                    btn_addFiles.Enabled = true;
                    btn_delete.Enabled = true;
                    progressBarControl1.Visible = false;
                    btn_upLoad.Enabled = true;
                    listView1.Items.Clear();
            }));
            
        }

        private void BUpdateFileForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isUpdatingFile &&
                XtraMessageBox.Show("正在上传文件，若关闭窗口将取消上传，您是否确定关闭？",
                "警告：",MessageBoxButtons.YesNo)== DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
            this.DialogResult = _hasAddNewFiles ? DialogResult.Yes : DialogResult.No;
        }
    }
}